package person.twj.jwt.core.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import person.twj.jwt.core.security.util.UserToken;
import person.twj.jwt.domain.po.SysUser;
import person.twj.jwt.service.ISysUserService;

import java.util.ArrayList;
import java.util.Collection;


/**
 * 校验前，从数据库中获取用户信息，包含密码
 */


public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private ISysUserService iSysUserService;


    // @TODO security:loadUserByUsername 1. 校验前，从数据库中获取用户信息，包含密码
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = iSysUserService.selectByUserName(username);
        if (user == null) {
            throw new BadCredentialsException("用户名或密码错误");
        } else {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            UserToken userToken = new UserToken(user.getUserId(),user.getUsername(), user.getPassword(), authorities);
//            userToken.setUserId(user.getUserId());
//            userToken.setPassword(user.getPassword());


            return userToken;


        }

    }
}
